import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';

import 'utils.dart';

/// 应用程序入口点
void main() {
  print("[APP] 应用程序启动");
  runApp(const MyApp());
}

/// MyApp 是应用程序的根组件
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    print("[MyApp] 构建应用程序根组件");
    return MaterialApp(
      title: 'Save image to gallery',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

/// MyHomePage 是应用程序的主页面
/// 展示了保存不同类型图像和视频的功能演示
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  _MyHomePageState createState() {
    print("[MyHomePage] 创建状态对象");
    return _MyHomePageState();
  }
}

class _MyHomePageState extends State<MyHomePage> {
  /// 用于捕获屏幕上组件的 GlobalKey
  final GlobalKey _globalKey = GlobalKey();

  @override
  void initState() {
    print("[_MyHomePageState] initState 初始化");
    super.initState();
    _requestPermissions();
  }

  /// 请求所需的权限
  void _requestPermissions() async {
    print("[权限] 开始请求所需权限");
    final permissions = await PermissionUtil.requestAll();
    print("[权限] 权限请求结果: $permissions");
  }

  @override
  Widget build(BuildContext context) {
    print("[_MyHomePageState] 构建UI界面");
    return Scaffold(
        appBar: AppBar(
          title: const Text("Save image to gallery"),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              const SizedBox(height: 15),
              // 使用 RepaintBoundary 包装要截图的组件
              RepaintBoundary(
                key: _globalKey,
                child: Container(
                  alignment: Alignment.center,
                  width: 300,
                  height: 300,
                  color: Colors.blue,
                ),
              ),
              Container(
                padding: const EdgeInsets.only(top: 15),
                width: 300,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveLocalImage,
                  child: const Text("Save Local Image"),
                ),
              ),
              Container(
                padding: const EdgeInsets.only(top: 15),
                width: 300,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveNetworkImage,
                  child: const Text("Save Network Image"),
                ),
              ),
              Container(
                padding: const EdgeInsets.only(top: 15),
                width: 300,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveNetworkGifFile,
                  child: const Text("Save Network Gif Image"),
                ),
              ),
              Container(
                padding: const EdgeInsets.only(top: 15),
                width: 300,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveNetworkVideoFile,
                  child: const Text("Save Network Video"),
                ),
              ),
            ],
          ),
        ));
  }

  /// 保存本地生成的图像
  /// 使用 RepaintBoundary 捕获屏幕上的组件并保存为图像
  _saveLocalImage() async {
    print("[本地图像] 开始保存本地图像");
    try {
      RenderRepaintBoundary boundary = _globalKey.currentContext!
          .findRenderObject() as RenderRepaintBoundary;
      print("[本地图像] 获取到 RenderRepaintBoundary 对象");

      ui.Image image = await boundary.toImage();
      print("[本地图像] 转换为 Image 对象成功");

      ByteData? byteData =
          await (image.toByteData(format: ui.ImageByteFormat.png));
      print("[本地图像] 获取 ByteData 成功，大小: ${byteData?.lengthInBytes ?? 0} 字节");

      if (byteData != null) {
        print("[本地图像] 准备调用 ImageGallerySaver.saveImage");
        final result =
            await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
        print("[本地图像] 保存结果: $result");
        Utils.toast(result.toString());
      } else {
        print("[本地图像] 错误: ByteData 为空");
        Utils.toast("保存失败: 无法获取图像数据");
      }
    } catch (e) {
      print("[本地图像] 保存过程中发生错误: $e");
      Utils.toast("保存失败: $e");
    }
  }

  /// 保存网络图像
  /// 从网络下载图像并保存到相册
  _saveNetworkImage() async {
    print("[网络图像] 开始下载并保存网络图像");
    try {
      print("[网络图像] 开始下载图像...");
      var response = await Dio().get(
          "https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg",
          options: Options(responseType: ResponseType.bytes));
      print("[网络图像] 下载完成，数据大小: ${response.data.length} 字节");

      print("[网络图像] 开始保存到相册...");
      final result = await ImageGallerySaver.saveImage(
          Uint8List.fromList(response.data),
          quality: 60,
          name: "hello");
      print("[网络图像] 保存结果: $result");
      Utils.toast("$result");
    } catch (e) {
      print("[网络图像] 下载或保存过程中发生错误: $e");
      Utils.toast("保存网络图像失败: $e");
    }
  }

  /// 保存网络 GIF 图像
  /// 先下载到临时目录，然后保存到相册
  _saveNetworkGifFile() async {
    print("[网络GIF] 开始下载并保存网络GIF文件");
    try {
      var appDocDir = await getTemporaryDirectory();
      String savePath = "${appDocDir.path}/temp.gif";
      print("[网络GIF] 临时保存路径: $savePath");

      String fileUrl =
          "https://hyjdoc.oss-cn-beijing.aliyuncs.com/hyj-doc-flutter-demo-run.gif";
      print("[网络GIF] 开始下载文件: $fileUrl");

      await Dio().download(fileUrl, savePath);
      print("[网络GIF] 下载完成，准备保存到相册");

      final result =
          await ImageGallerySaver.saveFile(savePath, isReturnPathOfIOS: true);
      print("[网络GIF] 保存结果: $result");
      Utils.toast("$result");
    } catch (e) {
      print("[网络GIF] 下载或保存过程中发生错误: $e");
      Utils.toast("保存GIF失败: $e");
    }
  }

  /// 保存网络视频
  /// 先下载到临时目录，然后保存到相册
  _saveNetworkVideoFile() async {
    print("[网络视频] 开始下载并保存网络视频文件");
    try {
      var appDocDir = await getTemporaryDirectory();
      String savePath = "${appDocDir.path}/temp.mp4";
      print("[网络视频] 临时保存路径: $savePath");

      String fileUrl =
          "https://s3.cn-north-1.amazonaws.com.cn/mtab.kezaihui.com/video/ForBiggerBlazes.mp4";
      print("[网络视频] 开始下载文件: $fileUrl");

      await Dio().download(fileUrl, savePath,
          onReceiveProgress: (count, total) {
        String percentage = "${(count / total * 100).toStringAsFixed(0)}%";
        print("[网络视频] 下载进度: $percentage");
      });
      print("[网络视频] 下载完成，准备保存到相册");

      final result = await ImageGallerySaver.saveFile(savePath);
      print("[网络视频] 保存结果: $result");
      Utils.toast("$result");
    } catch (e) {
      print("[网络视频] 下载或保存过程中发生错误: $e");
      Utils.toast("保存视频失败: $e");
    }
  }
}
